<?php
namespace app\member\controller;
use think\Db;
use jwt\Jwt;

class Device extends Common{
    function __construct(){
        parent::__construct();
        $this->assign('_nav',json_encode(config("navs.1.children"),JSON_UNESCAPED_UNICODE));
    }
    function index($val='',$type='name'){
        $where=['member_id'=>$this->user['id']];
        if($val){
            $where[$type]=[$type,'like',"%$val%"];
        }
        $params=[
            'val'=>$val,
            'type'=>$type,
        ];
        
        $list=model($this->table)->readAll($where,true);
        $list->appends($params);
        $this->assign('list',$list);
        $this->assign('params',$params);
        //p($list->toArray());
        return view();
    }
    // 设备添加
    function add($id=0){
        $user=$this->user;
        $device=[];
        if($id>0){
            $device=model($this->table)->read(['id'=>$id,'member_id'=>$user['id']]);//该项不存在或不属于该用户 做添加操作
            if(empty($device)){
                $id=0;
            }
        }  
        if(request()->isPost()){
            $data=[
                'id'=>$id,
                'name'=>input('name/s',''),
                'login_name'=>input('login_name/s',''),
                'sex'=>input('sex/d',2),
                'version'=>input('version/s',''),
                'udid'=>input('udid/s',''),
                'tel'=>input('tel/s',''),
            ];
            // $hasLoginName=$this->hasLoginName($data['login_name'],$id);
            // if($hasLoginName){
            //     $this->error('登录名重复');
            // }
            $operation=[];
            $data['s_time']=time();
            if($id>0){
                $operation=model($this->table)->edit($data);
            }else{

                // 查找用户表，获取该用户的设备上限值
                $member = Db::name('member')->where('id','eq',$user['id'])->field('id,max_device')->find();
                $limit = $member['max_device'];
                // 统计已有设备数量
                $quant = Db::name('device')->where('member_id','eq',$user['id'])->count();
                // echo json_encode($quant);die;
                if ($limit <= $quant) {
                    $this->error('添加失败！设备已达到上限！');
                }
            
          
                $data['member_id']=$user['id'];
                $operation=model($this->table)->add($data);
            }
            if(empty($operation)){
                $this->error(lang('Failed operation'));
            }
            $this->success(lang('Successful operation'));
        }
    }
    // 用于Excel 导入设备 操作
    function addAll(){
        if(request()->isPost()){
            $data=input('data/a',[]);
            if(empty($data)||!is_integer(key($data))){
                $this->error(lang('The data does not exist or the format is incorrect'));
            }
            $time=time();
            $member_id=$this->user['id'];
            foreach ($data as $k => $v) {
                $data[$k]=[
                    'name'=>$v[0],
                    'login_name'=>$v[1],
                    'version'=>$v[2],
                    'sex'=>$v[3],
                    'tel'=>$v[4],
                    'udid'=>$v[5],
                    's_time'=>$time,
                    'member_id'=>$member_id,
                ];
            }
            $add=model($this->table)->add($data);
            
            if(empty($add)){
                $this->error(lang('Failed operation'));
            }
            $this->success(lang('Successful operation'));
        }
    }
    function del($id=0){
        if(request()->isAjax()||request()->isPost()){
            $ids=input('ids/a',[]); // 多项删除
            if($id<=0&&empty($ids)){
                $this->error(lang('Data does not exist'));
            }
            $member_id=$this->user['id'];
            $where=['id'=>$id,'member_id'=>$member_id];
            $_map=['device_id'=>$id];
            $_map2=['dev_id'=>$id];
            if(!empty($ids)){
                $where=[
                    'member_id'=>$member_id,
                    'id'=>['id','in',$ids]
                ];
                $_map=[
                    'device_id'=>['device_id','in',$ids]
                ];
                $_map2=[
                    'dev_id'=>['dev_id','in',$ids]
                ];
            }
            
            $del=model($this->table)->del($where);
            if($del){
                // 删除该设备上的账号 
                $softs=model('software')->readAll($_map,0,['field'=>'id']);
                model('software')->del($_map);
                if(count($softs)){
                    $soft_ids=[];
                    foreach ($softs as $k => $v) {
                        $soft_ids[]=$v['id'];
                    }
                    // 删除该设备上的账号对应的好友
                    model('social')->del(['soft_id'=>['soft_id','in',$soft_ids]]);
                }
                // 删除该设备上的任务列表
                model('task_device')->del($_map);
                // 删除该设备上存在的微信记录信息
                model('weixinlogs')->del($_map2);
                $this->success(lang('Successful operation'));
                die;
            }
            $this->error(lang('Failed operation'));
        }
    }
    function close($id=0){
        if(request()->isAjax()||request()->isPost()){
            $ids=input('ids/a',[]); // 多项
            if($id<=0&&empty($ids)){
                $this->error(lang('Data does not exist'));
            }
            $member_id=$this->user['id'];
            $where=" `member_id`={$member_id} ";
            if(!empty($ids)){
                $ids=implode(',', $ids);
                $where.=" and `id` in ({$ids}) ";
            }else{
                $where.=" and `id`={$id} ";
            }
            $rs=model('device')->close($where,'status',true);
            if($rs){
                $this->success(lang('Successful operation'));
                die;
            }
            $this->error(lang('Failed operation'));
        }
    }
    // 验证设备名称是否重复？
    function hasLoginName($name='',$id=0){
        if(empty($name)){
            return true;
        }
        $where=[
            'login_name'=>$name,
            'member_id'=>$this->user['id']
        ];
        if($id>0){
            $where['id']=['id','neq',$id];
        }
        $has=model($this->table)->read($where);
        if($has){
            return true;
        }
    }
    /**
     * 设备调试（模拟移动端 接收、完成任务）
     * @param  integer $dev 设备ID
     * @return view
     */
    function debug($dev=0){
        if($dev<=0){
            $this->error('设备不存在');
        }
        $member_id=$this->user['id'];
        $has=model('device')->read(['id'=>$dev,'member_id'=>$member_id]);
        if(empty($has)){
            $this->error('设备不存在');
        }
        $this->assign('device',$has);
        $this->assign('_action','index');
        $rs['id']=$member_id;
        $rs['_loginTime']=time();
        $t=Jwt::encode($rs);
        $rs['token']=$t['data'];
        $this->assign('token',$rs['token']);
        return view();
    }

}
